package com.ssky.bean.validator;

import com.ssky.bean.validator.core.FieldValidator;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: ssky
 * @Date: 2021/07/29
 * @Description:
 */
public class FieldValidatorCache {
    private final Map<String, FieldValidator> validatorMap;
    private static volatile FieldValidatorCache instance;
    ReadWriteLock lock = new ReentrantReadWriteLock();

    Lock readlock = this.lock.readLock();

    Lock writelock = this.lock.writeLock();

    private FieldValidatorCache() {
        this.validatorMap = new HashMap<>();
    }

    public static FieldValidatorCache getSingleInstance() {
        if (instance == null) {
            synchronized (FieldValidatorCache.class) {
                if (instance == null) {
                    instance = new FieldValidatorCache();
                }
            }
        }
        return instance;
    }

    public FieldValidator get(String id) {
        this.readlock.lock();
        try {
            return this.validatorMap.get(id);
        } finally {
            this.readlock.unlock();
        }
    }


    public void put(String id, FieldValidator fieldValidator) {
        this.writelock.lock();
        try {
            this.validatorMap.put(id, fieldValidator);
        } finally {
            this.writelock.unlock();
        }
    }

    public Set<String> getIdAll() {
        this.readlock.lock();
        try {
            Set<String> keySet = this.validatorMap.keySet();
            return keySet;
        } finally {
            this.readlock.unlock();
        }
    }
}
